<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\StoreApply;
use App\Models\Store;
use App\Models\StoreCategory;
use App\Models\Address;
use App\Models\PickupPointApplication;
use App\Models\PickupPointVendor;
use App\Models\Vendor;
use App\Models\Member;
use App\Models\StaffAuth;
use App\Models\HhmCoinCorpQuota;
use App\Services\ImageUrlService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Schema;

class StoreController extends Controller
{
    const informationThumbImgTag1 = '<img src=';
    const informationThumbImgTag2 = ' width="100%"/>';

    /**
     * 提交门店申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function apply(Request $request)
    {
        // 从 param 字段中获取 apply 数据
        $param = $request->input('param');
        $apply_store_data = $param['apply'] ?? null;
        
        // 检查数据是否存在
        if (!$apply_store_data) {
            return response()->json([
                'code' => 0,
                'message' => '请提供申请数据'
            ]);
        }
        
        $str = '';
        
        if (!empty($apply_store_data['aptitudeImg'])) {
            $str = '<p>';
            foreach ($apply_store_data['aptitudeImg'] as $value) {
                $str .= self::informationThumbImgTag1 . $value . self::informationThumbImgTag2;
            }
            $str .= '</p>';
        }

        // 从请求中获取用户ID
        $uid = $param['user_id'] ?? $request->input('user_id')||1;
        if (!$uid) {
            return response()->json([
                'code' => 0,
                'message' => '请提供用户ID'
            ]);
        }
        
        // 查询已有审核通过或者审核中的记录
        $has = StoreApply::where('uid', $uid)->whereIn('status', [0, 1])->count();
        if ($has) {
            return response()->json([
                'code' => 0,
                'message' => '您已提交过申请'
            ]);
        }

        $apply = [
            'uniacid' => 1, // 默认应用ID
            'uid' => $uid,
            'username' => trim($apply_store_data['username'] ?? ''),
            'password' => $apply_store_data['password'] ?? '',
            'realname' => $apply_store_data['realname'] ?? '',
            'mobile' => $apply_store_data['mobile'] ?? '',
            'status' => 0,
            // 将信息字段改为统一规范化后的数组（由模型访问器进行 JSON 存储）
            'information' => $this->normalizeApplyInformation($apply_store_data, $str),
            'order_id' => 0,
            'validity' => 0,
            'salt' => '',
            'pwd' => $apply_store_data['password'] ?? '', // 保存明文密码
        ];
        
        if (!$apply['password']) {
            return response()->json([
                'code' => 0,
                'message' => '请输入密码'
            ]);
        }

        // 检查营业执照
        $is_business_license = config('store.is_business_license', 1);
        if (($is_business_license != '0') && empty($apply_store_data['aptitudeImg'])) {
            return response()->json([
                'code' => 0,
                'message' => '请上传营业执照'
            ]);
        }

        // 检查用户名是否已存在
        $existingUser = StoreApply::where('username', $apply_store_data['username'] ?? '')->first();
        if ($existingUser) {
            return response()->json([
                'code' => 0,
                'message' => '该用户名已存在系统'
            ]);
        }

        // 加密密码
        $apply['salt'] = Str::random(8);
        $apply['password'] = Hash::make($apply['password']);
        
        $store_apply_model = new StoreApply();
        $store_apply_model->fill($apply);
        $store_apply_model->save();

        return response()->json([
            'code' => 1,
            'message' => '提交申请成功,等待审核'
        ]);
    }

    /**
     * 判断是否可以申请门店
     * @return \Illuminate\Http\JsonResponse
     */

    // 门店申请信息规范化（类内私有方法）
    private function normalizeApplyInformation(array $apply, string $informationThumbHtml = ''): array
    {
        $padTime = function ($t) {
            if (!$t) return '';
            if (preg_match('/^\d{1,2}:\d{1,2}$/', $t)) {
                [$h, $m] = explode(':', $t);
                $h = str_pad((string)intval($h), 2, '0', STR_PAD_LEFT);
                $m = str_pad((string)intval($m), 2, '0', STR_PAD_LEFT);
                return "$h:$m";
            }
            return $t;
        };

        $toInt = function ($v) {
            if ($v === '' || $v === null) return 0;
            return intval($v);
        };

        $toString = function ($v) {
            if ($v === null) return '';
            return is_scalar($v) ? (string)$v : '';
        };

        $toStringArray = function ($arr) {
            if (!is_array($arr)) return [];
            return array_values(array_filter(array_map(function ($x) {
                return is_scalar($x) ? trim((string)$x) : '';
            }, $arr), function ($x) { return $x !== ''; }));
        };

        // banner 统一为字符串（如果为数组则取第一个非空）
        $banner = $apply['bannerImg'] ?? '';
        if (is_array($banner)) {
            $banner = $toString(array_values(array_filter($banner, function ($x) { return !empty($x); }))[0] ?? '');
        } else {
            $banner = $toString($banner);
        }

        $commission = $apply['shop_commission'] ?? null;

        return [
            'store_name' => $toString($apply['storeName'] ?? ''),
            'thumb' => $toString($apply['storeImg'] ?? ''),
            'banner_thumb' => $banner,
            'category_id' => $toInt($apply['categoryId'] ?? 0),
            'province_id' => $toInt($apply['provinceId'] ?? 0),
            'city_id' => $toInt($apply['cityId'] ?? 0),
            'district_id' => $toInt($apply['districtId'] ?? 0),
            'street_id' => $toInt($apply['streetId'] ?? 0),
            'address' => $toString($apply['address'] ?? ''),
            'lng' => $toString($apply['lng'] ?? ''),
            'lat' => $toString($apply['lat'] ?? ''),
            'business_hours_start' => $padTime($apply['beginTime'] ?? ''),
            'business_hours_end' => $padTime($apply['endTime'] ?? ''),
            'aptitude_imgs' => $toStringArray($apply['aptitudeImg'] ?? []),
            'id_card_imgs' => $toStringArray($apply['idCardImg'] ?? []),
            'other_imgs' => $toStringArray($apply['otherImg'] ?? []),
            'remark' => $toString($apply['remark'] ?? ''),
            'store_introduce' => $toString($apply['storeIntroduce'] ?? ''),
            'information_thumb' => $toString($informationThumbHtml ?: ''),
            'shop_commission' => is_numeric($commission) ? (float)$commission : 0.0,
            'location_name' => $toString($apply['location_name'] ?? ''),
        ];
    }

    public function verifyApply()
    {
        return response()->json([
            'code' => 1,
            'message' => '可以进行申请'
        ]);
    }

    /**
     * 获取门店申请信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreApply(Request $request)
    {
        $param = $request->input('param');
        $uid = $param['user_id'] ?? $request->input('user_id');
        
        // 添加调试信息
        $debug_info = [
            'param_user_id' => $param['user_id'] ?? null,
            'request_user_id' => $request->input('user_id'),
            'final_uid' => $uid,
            'request_all' => $request->all()
        ];
        
        if (!$uid) {
            return response()->json([
                'code' => 0,
                'message' => '请提供用户ID',
                'debug' => $debug_info
            ]);
        }
        
        // 查询申请记录，添加调试信息
        $apply_model = StoreApply::where('uid', $uid)->first();
        
        // 添加查询调试信息
        $query_debug = [
            'uid' => $uid,
            'uid_type' => gettype($uid),
            'total_records' => StoreApply::count(),
            'records_with_uid' => StoreApply::where('uid', $uid)->count(),
            'all_uids' => StoreApply::pluck('uid')->toArray(),
            'found_record' => $apply_model ? true : false
        ];
        
        if (!$apply_model) {
            return response()->json([
                'code' => 0,
                'message' => '未找到申请记录',
                'debug' => $debug_info,
                'query_debug' => $query_debug
            ]);
        }
        
        // 构建返回数据，包含密码信息
        $data = [
            'id' => $apply_model->id,
            'uid' => $apply_model->uid,
            'username' => $apply_model->username,
            'mobile' => $apply_model->mobile,
            'realname' => $apply_model->realname,
            'status' => $apply_model->status,
            'password' => $apply_model->pwd, // 返回明文密码
            'created_at' => $apply_model->created_at,
            'updated_at' => $apply_model->updated_at,
            'information' => $apply_model->information
        ];
        
        return response()->json([
            'code' => 1,
            'message' => '获取申请信息成功',
            'data' => $data,
            'debug' => $debug_info,
            'query_debug' => $query_debug
        ]);
    }

    /**
     * 判断会员门店申请状态
     * @return \Illuminate\Http\JsonResponse
     */
    public function verifyApplyStatus(Request $request)
    {
        $param = $request->input('param');
        $uid = $param['user_id'] ?? $request->input('user_id');
        if (!$uid) {
            return response()->json([
                'code' => 0,
                'message' => '请提供用户ID'
            ]);
        }
        
        $store = Store::where('uid', $uid)->first();
        if ($store) {
            return response()->json([
                'code' => 1,
                'message' => '已经是门店,不能重复申请',
                'data' => [
                    'status' => 3,
                    'store_id' => $store->id  // 返回门店ID供前端缓存
                ]
            ]);
        }

        $apply_model = StoreApply::where('uid', $uid)->first();

        if ($apply_model && $apply_model->status == 0) {
            return response()->json([
                'code' => 1,
                'message' => '已提交申请,等待审核',
                'data' => [
                    'username' => $apply_model->username,
                    'mobile' => $apply_model->mobile,
                    'password' => $apply_model->pwd,
                    'status' => 2
                ]
            ]);
        }

        $res = [
            'status' => 1,
            'last_info' => []
        ];

        // 驳回状态处理
        if ($apply_model && $apply_model->status == -1) {
            $res['status'] = -1;
            $information = json_decode(json_encode($apply_model->information), true);

            $information_2 = [
                'province' => Address::where('id', $information['province_id'])->value('areaname'),
                'city' => Address::where('id', $information['city_id'])->value('areaname'),
                'district' => Address::where('id', $information['district_id'])->value('areaname'),
                'store_category_text' => StoreCategory::where('id', $information['category_id'])->value('name')
            ];

            $information_thumb_str = strip_tags($information['information_thumb'], '<img>');
            $information_thumb_data = explode(self::informationThumbImgTag2, $information_thumb_str);
            $information['information_thumb'] = array_filter(array_map(function ($item) {
                return ltrim($item, self::informationThumbImgTag1);
            }, $information_thumb_data));

            $res['last_info'] = [
                'username' => $apply_model->username,
                'realname' => $apply_model->realname,
                'mobile' => $apply_model->mobile,
                'password' => $apply_model->pwd,
                'information' => array_merge($information, $information_2)
            ];
        }

        return response()->json([
            'code' => 1,
            'message' => '可以进行申请',
            'data' => $res
        ]);
    }

    /**
     * 获取门店分类列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreCategorys()
    {
        try {
            $store_categorys = StoreCategory::select('id', 'name', 'thumb', 'sort', 'is_open')
                ->where('is_open', 1)
                ->orderBy('sort', 'asc')
                ->get();
            
            // 处理图片路径
            foreach ($store_categorys as &$category) {
                if ($category['thumb']) {
                    $category['thumb'] = ImageUrlService::processImageUrl($category['thumb']);
                }
            }
            
            return response()->json([
                'code' => 1,
                'message' => '门店分类获取成功',
                'data' => $store_categorys
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '获取门店分类失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $attach = $request->input('attach', '');
            
            // 根据附件类型选择存储目录
            $storagePath = 'store_apply';
            if ($attach === 'storefront') {
                $storagePath = 'storefront';
            } elseif ($attach === 'license') {
                $storagePath = 'license';
            }else{
                $storagePath=$attach;
            }
            
            // 验证文件类型
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
            $extension = $file->getClientOriginalExtension();
            if(!$extension){
                $extension = 'png';
            }
            if (!in_array(strtolower($extension), $allowedTypes)) {
                return response()->json([
                    'code' => 0,
                    'message' => '不支持的文件类型，请上传图片文件'
                ]);
            }
            
            // 验证文件大小 (最大5MB)
            if ($file->getSize() > 5 * 1024 * 1024) {
                return response()->json([
                    'code' => 0,
                    'message' => '文件大小不能超过5MB'
                ]);
            }
            
            // 生成唯一文件名
            $filename = time() . '_' . uniqid() . '.' . $extension;
            $path = $file->storeAs($storagePath, $filename, 'public');
            
            // 生成压缩图
            try {
                $this->generateCompressedImage($storagePath, $filename);
            } catch (\Exception $e) {
                \Log::warning('生成压缩图失败', [
                    'file' => $filename,
                    'error' => $e->getMessage()
                ]);
                // 压缩失败不影响上传成功
            }
            
            return response()->json([
                'code' => 1,
                'message' => '上传成功',
                'data' => [
                    'img' => asset('storage/' . $path),
                    'attach' => $attach,
                    'filename' => $filename,
                    'original_name' => $file->getClientOriginalName()
                ]
            ]);
        }

        return response()->json([
            'code' => 0,
            'message' => '上传失败，请选择文件'
        ]);
    }
    
    /**
     * 生成压缩图
     * @param string $storagePath 存储目录
     * @param string $filename 文件名
     * @throws \Exception
     */
    private function generateCompressedImage(string $storagePath, string $filename): void
    {
        $disk = \Storage::disk('public');
        $sourcePath = $storagePath . '/' . $filename;
        $targetPath = $storagePath . '_small/' . $filename;
        
        // 检查源文件是否存在
        if (!$disk->exists($sourcePath)) {
            throw new \Exception("源文件不存在: {$sourcePath}");
        }
        
        // 确保目标目录存在
        $targetDir = $storagePath . '_small';
        if (!$disk->exists($targetDir)) {
            $disk->makeDirectory($targetDir, 0755, true);
        }
        
        // 获取完整路径
        $sourceFullPath = $disk->path($sourcePath);
        $targetFullPath = $disk->path($targetPath);
        
        // 使用 GD 库生成压缩图
        $this->compressImageWithGD($sourceFullPath, $targetFullPath, 100);
        
        \Log::info('压缩图生成成功', [
            'source' => $sourcePath,
            'target' => $targetPath
        ]);
    }
    
    /**
     * 使用 GD 库压缩图片
     * @param string $sourcePath 源图片路径
     * @param string $targetPath 目标图片路径
     * @param int $size 缩略图尺寸
     * @throws \Exception
     */
    private function compressImageWithGD(string $sourcePath, string $targetPath, int $size): void
    {
        // 标准化路径
        $sourcePath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $sourcePath);
        $targetPath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $targetPath);
        
        // 检查源文件是否存在
        if (!file_exists($sourcePath)) {
            throw new \Exception("源图片文件不存在: {$sourcePath}");
        }
        
        // 获取原始图片信息
        $imageInfo = getimagesize($sourcePath);
        if (!$imageInfo) {
            throw new \Exception("无法获取图片信息，文件可能损坏: {$sourcePath}");
        }

        $originalWidth = $imageInfo[0];
        $originalHeight = $imageInfo[1];
        $mimeType = $imageInfo['mime'];

        // 根据 MIME 类型创建图片资源
        switch ($mimeType) {
            case 'image/jpeg':
                $sourceImage = imagecreatefromjpeg($sourcePath);
                break;
            case 'image/png':
                $sourceImage = imagecreatefrompng($sourcePath);
                break;
            case 'image/gif':
                $sourceImage = imagecreatefromgif($sourcePath);
                break;
            default:
                throw new \Exception("不支持的图片格式: {$mimeType}");
        }

        if (!$sourceImage) {
            throw new \Exception("无法创建图片资源");
        }

        // 创建缩略图画布
        $thumbnail = imagecreatetruecolor($size, $size);
        
        // 根据图片格式设置背景
        if ($mimeType === 'image/png') {
            // PNG格式：透明背景
            imagealphablending($thumbnail, false);
            imagesavealpha($thumbnail, true);
            $transparent = imagecolorallocatealpha($thumbnail, 0, 0, 0, 127);
            imagefill($thumbnail, 0, 0, $transparent);
        } else {
            // JPG等其他格式：白色背景
            $white = imagecolorallocate($thumbnail, 255, 255, 255);
            imagefill($thumbnail, 0, 0, $white);
        }

        // 计算缩放比例（保持宽高比，居中裁剪）
        $scale = max($originalWidth / $size, $originalHeight / $size);
        $newWidth = $originalWidth / $scale;
        $newHeight = $originalHeight / $scale;
        
        $offsetX = ($size - $newWidth) / 2;
        $offsetY = ($size - $newHeight) / 2;

        // 复制并缩放图片
        imagecopyresampled(
            $thumbnail, $sourceImage,
            $offsetX, $offsetY, 0, 0,
            $newWidth, $newHeight,
            $originalWidth, $originalHeight
        );

        // 保存缩略图
        $success = false;
        switch ($mimeType) {
            case 'image/jpeg':
                $success = imagejpeg($thumbnail, $targetPath, 80);
                break;
            case 'image/png':
                $success = imagepng($thumbnail, $targetPath, 8);
                break;
            case 'image/gif':
                $success = imagegif($thumbnail, $targetPath);
                break;
        }

        // 清理内存
        imagedestroy($sourceImage);
        imagedestroy($thumbnail);

        if (!$success) {
            throw new \Exception("保存缩略图失败: {$targetPath}");
        }
    }


    /**
     * 获取自提点申请状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pickupPointStatus(Request $request)
    {
        try {
            // 获取用户ID
            $uid = $request->input('user_id');
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID'
                ]);
            }

            // 查询用户是否有门店信息
            $store = Store::where('uid', $uid)->first();
            
            if (!$store) {
                return response()->json([
                    'code' => 0,
                    'message' => '您还没有门店信息，请先申请门店入驻'
                ]);
            }

            // 查询用户是否有申请记录
            $application = PickupPointApplication::where('store_id', $store->id)
                ->orderBy('created_at', 'desc')
                ->first();

            // 如果没有申请记录，返回门店信息用于申请
            if (!$application) {
                return response()->json([
                    'code' => 1,
                    'message' => 'ok',
                    'data' => [
                        'has_application' => false,
                        'status' => 'no_application',
                        'store_info' => [
                            'store_name' => $store->store_name,
                            'address' => $this->getStoreAddress($store),
                            'phone' => $store->mobile ?? '',
                            'member_id' => $uid,
                            'store_id' => $store->id
                        ]
                    ]
                ]);
            }

            // 根据申请状态返回不同信息
            switch ($application->status) {
                case PickupPointApplication::STATUS_PENDING:
                    return response()->json([
                        'code' => 1,
                        'message' => 'ok',
                        'data' => [
                            'has_application' => true,
                            'status' => 'pending',
                            'status_text' => '申请中',
                            'application_id' => $application->id,
                            'submitted_at' => $application->submitted_at ? $application->submitted_at->format('Y-m-d H:i:s') : '',
                            'message' => '提交成功，后台审核中!'
                        ]
                    ]);

                case PickupPointApplication::STATUS_REJECTED:
                    return response()->json([
                        'code' => 1,
                        'message' => 'ok',
                        'data' => [
                            'has_application' => true,
                            'status' => 'rejected',
                            'status_text' => '已驳回',
                            'application_id' => $application->id,
                            'rejected_at' => $application->reviewed_at ? $application->reviewed_at->format('Y-m-d H:i:s') : '',
                            'reject_reason' => $application->reason ?? '审核不通过',
                            'can_resubmit' => true
                        ]
                    ]);

                case PickupPointApplication::STATUS_APPROVED:
                    return response()->json([
                        'code' => 1,
                        'message' => 'ok',
                        'data' => [
                            'has_application' => true,
                            'status' => 'approved',
                            'status_text' => '审核通过',
                            'application_id' => $application->id,
                            'submitted_at' => $application->submitted_at ? $application->submitted_at->format('Y-m-d H:i:s') : '',
                            'approved_at' => $application->reviewed_at ? $application->reviewed_at->format('Y-m-d H:i:s') : '',
                            'pickup_point_status' => $application->pickup_point_status,
                            'message' => '恭喜您，申请已通过审核！'
                        ]
                    ]);

                default:
                    return response()->json([
                        'code' => 0,
                        'message' => '未知的申请状态'
                    ]);
            }

        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '获取申请状态失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 提交自提点申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pickupPointSubmit(Request $request)
    {
        try {
            // 获取用户ID
            $uid = $request->input('user_id');
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID'
                ]);
            }

            // 验证用户是否有门店
            $store = Store::where('uid', $uid)->first();
            if (!$store) {
                return response()->json([
                    'code' => 0,
                    'message' => '您还没有门店信息，请先申请门店入驻'
                ]);
            }

            // 检查是否已有申请记录
            $existingApplication = PickupPointApplication::where('store_id', $store->id)
                ->whereIn('status', [PickupPointApplication::STATUS_PENDING, PickupPointApplication::STATUS_APPROVED])
                ->first();

            if ($existingApplication) {
                return response()->json([
                    'code' => 0,
                    'message' => '您已有申请记录，请勿重复提交'
                ]);
            }

            // 创建申请记录，只需要门店ID
            $application = new PickupPointApplication();
            $application->store_id = $store->id;
            $application->status = PickupPointApplication::STATUS_PENDING;
            $application->pickup_point_status = PickupPointApplication::PICKUP_STATUS_ALLOW;
            $application->submitted_at = now();
            $application->save();

            return response()->json([
                'code' => 1,
                'message' => '申请提交成功',
                'data' => [
                    'application_id' => $application->id,
                    'status' => 'pending'
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '提交申请失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 重新提交自提点申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pickupPointResubmit(Request $request)
    {
        try {
            // 获取用户ID
            $uid = $request->input('user_id');
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID'
                ]);
            }

            // 验证用户是否有门店
            $store = Store::where('uid', $uid)->first();
            if (!$store) {
                return response()->json([
                    'code' => 0,
                    'message' => '您还没有门店信息，请先申请门店入驻'
                ]);
            }

            $applicationId = $request->input('application_id');
            if (!$applicationId) {
                return response()->json([
                    'code' => 0,
                    'message' => '申请ID不能为空'
                ]);
            }

            // 查找原申请记录
            $originalApplication = PickupPointApplication::where('id', $applicationId)
                ->where('store_id', $store->id)
                ->first();

            if (!$originalApplication) {
                return response()->json([
                    'code' => 0,
                    'message' => '申请记录不存在'
                ]);
            }

            if ($originalApplication->status !== PickupPointApplication::STATUS_REJECTED) {
                return response()->json([
                    'code' => 0,
                    'message' => '只有被驳回的申请才能重新提交'
                ]);
            }

            // 更新申请状态为待审核
            $originalApplication->status = PickupPointApplication::STATUS_PENDING;
            $originalApplication->submitted_at = now();
            $originalApplication->reason = null; // 清空驳回原因
            $originalApplication->save();

            return response()->json([
                'code' => 1,
                'message' => '重新申请提交成功',
                'data' => [
                    'application_id' => $originalApplication->id,
                    'status' => 'pending'
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '重新提交申请失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取会员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMemberInfo(Request $request)
    {
        try {
            // 从 param 字段中获取 user_id，如果没有则从最外层获取
            $param = $request->input('param', []);
            $uid = $param['user_id'] ?? $request->input('user_id');
            
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID'
                ]);
            }

            // 查询会员信息
            $member = Member::where('uid', $uid)->first();
            
            if (!$member) {
                return response()->json([
                    'code' => 0,
                    'message' => '用户不存在'
                ]);
            }

            // 构建返回数据
            $memberInfo = [
                'uid' => $member->uid,
                'name' => $member->realname ?? $member->nickname ?? '未知用户',
                'nickname' => $member->nickname ?? '',
                'realname' => $member->realname ?? '',
                'avatar' => $member->avatar ? (strpos($member->avatar, 'http') === 0 ? $member->avatar : asset('storage/' . $member->avatar)) : '/static/images/default-avatar.png',
                'mobile' => $member->mobile ?? '',
                'email' => $member->email ?? '',
                'memberLevel' => $this->getMemberLevel($member),
                'gender' => $member->gender ?? 0,
                'birthday' => $member->birthday ?? '',
                'address' => $member->address ?? '',
                'created_at' => $member->created_at ? $member->created_at->format('Y-m-d H:i:s') : '',
                'updated_at' => $member->updated_at ? $member->updated_at->format('Y-m-d H:i:s') : ''
            ];

            // 查询员工授权信息
            $staffAuth = StaffAuth::where('uid', $uid)
                ->where('status', StaffAuth::STATUS_AUTHORIZED)
                ->whereNull('deleted_at')
                ->first();

            $memberInfo['is_staff'] = (bool) $staffAuth;
            $memberInfo['staff_info'] = $staffAuth ? [
                'store_id' => $staffAuth->store_id,
                'status' => $staffAuth->status,
                'status_text' => $staffAuth->status_text,
                'authorized_at' => $staffAuth->created_at ? date('Y-m-d H:i:s', $staffAuth->created_at) : '',
            ] : null;

            // 确定关联门店ID：优先使用员工授权的门店，否则使用用户自己的门店
            $relatedStoreId = $staffAuth->store_id ?? Store::query()->where('uid', $uid)->value('id');

            // 查询授信额度（基于门店ID）
            $quota = null;
            if ($relatedStoreId) {
                $quota = HhmCoinCorpQuota::where('store_id', $relatedStoreId)
                    ->orderByDesc('id')
                    ->first();
            }

            $statusTextMap = [
                0 => '未激活',
                1 => '待审核',
                2 => '已激活',
                3 => '冻结',
                4 => '审核不通过'
            ];

            $memberInfo['credit_activation'] = $quota ? [
                'store_id' => $relatedStoreId,
                'status' => (int) $quota->status,
                'status_text' => $statusTextMap[$quota->status] ?? '未知状态',
                'total_quota' => $quota->num,
                'used_quota' => $quota->num - $quota->stock_num,
                'remaining_quota' => $quota->stock_num,
                'audit_passed_at' => $quota->audit_passed_at ? date('Y-m-d H:i:s', $quota->audit_passed_at) : '',
            ] : null;

            return response()->json([
                'code' => 1,
                'message' => '获取会员信息成功',
                'data' => $memberInfo
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '获取会员信息失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取会员等级
     * @param Member $member
     * @return string
     */
    private function getMemberLevel($member)
    {
        // 根据会员的积分或其他条件判断会员等级
        // 这里可以根据实际业务逻辑来定义会员等级
        $points = $member->points ?? 0;
        
        if ($points >= 10000) {
            return '钻石会员';
        } elseif ($points >= 5000) {
            return '黄金会员';
        } elseif ($points >= 1000) {
            return '白银会员';
        } else {
            return '普通会员';
        }
    }

    /**
     * 获取门店信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreInfo(Request $request)
    {
        try {
            // 获取用户ID
            $param = $request->input('param');
            $uid = $param['user_id'] ?? $request->input('user_id');
            
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID'
                ]);
            }

            // 查询用户是否有门店信息
            $store = Store::where('uid', $uid)->first();
            
            if (!$store) {
                return response()->json([
                    'code' => 0,
                    'message' => '您还没有门店信息，请先申请门店入驻'
                ]);
            }

            // 返回门店信息
            return response()->json([
                'code' => 1,
                'message' => '获取门店信息成功',
                'data' => [
                    'store_name' => $store->store_name,
                    'address' => $this->getStoreAddress($store),
                    'phone' => $store->mobile ?? '',
                    'member_id' => $uid,
                    'store_id' => $store->id
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '获取门店信息失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取门店地址
     * @param Store $store
     * @return string
     */
    private function getStoreAddress($store)
    {
        $address = '';
        
        // 构建完整地址
        if ($store->province_id && $store->province) {
            $address .= $store->province->areaname . ' ';
        }
        if ($store->city_id && $store->city) {
            $address .= $store->city->areaname . ' ';
        }
        if ($store->district_id && $store->district) {
            $address .= $store->district->areaname . ' ';
        }
        if ($store->address) {
            $address .= $store->address;
        }
        
        return trim($address) ?: '请填写详细地址';
    }

    /**
     * 获取供应商清单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVendorList(Request $request)
    {
        try {
            // 获取用户ID
            $param = $request->input('param');
            $uid = $param['user_id'] ?? $request->input('user_id');
            
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID'
                ]);
            }

            // 查询用户是否有门店信息
            $store = Store::where('uid', $uid)->first();
            
            if (!$store) {
                return response()->json([
                    'code' => 0,
                    'message' => '您还没有门店信息，请先申请门店入驻'
                ]);
            }

            // 查询门店关联的供应商
            $pickupPointVendors = PickupPointVendor::with(['vendor' => function($query) {
                $query->withTrashed(); // 包含软删除的记录
            }])
            ->where('store_id', $store->id)
            ->get();
            
            // 手动过滤 status = 1 的供应商
            $pickupPointVendors = $pickupPointVendors->filter(function($item) {
                return $item->vendor && $item->vendor->status == 1;
            });

            // 构建供应商列表数据
            $vendorList = [];
            foreach ($pickupPointVendors as $pickupPointVendor) {
                if ($pickupPointVendor->vendor) {
                    $vendor = $pickupPointVendor->vendor;
                    
                    // 获取联系人信息
                    $contactPerson = '';
                    $contactPhone = $vendor->mobile;
                    
                    if ($vendor->applicant) {
                        $contactPerson = $vendor->applicant->realname ?? $vendor->applicant->nickname ?? '联系人';
                    } else {
                        $contactPerson = $vendor->real_name ?: '联系人';
                    }
                    
                    // 获取关联员工信息（这里需要根据实际业务逻辑调整）
                    $staffInfo = [
                        'name' => '李小明', // 示例数据，需要根据实际业务逻辑获取
                        'id' => '386259'   // 示例数据，需要根据实际业务逻辑获取
                    ];
                    
                    $vendorList[] = [
                        'id' => $vendor->id,
                        'supplier_name' => $vendor->supplier_name,
                        'contact_person' => $contactPerson,
                        'contact_phone' => $contactPhone,
                        'address' => $vendor->full_address,
                        'staff_info' => $staffInfo,
                        'created_at' => $vendor->created_at
                    ];
                }
            }

            // 获取用户信息
            $member = Member::where('uid', $uid)->first();
            $userInfo = [
                'name' => $member ? ($member->realname ?: $member->nickname ?: '未知用户') : '未知用户',
                'avatar' => $member ? ($member->avatar ?: '/static/images/default-avatar.png') : '/static/images/default-avatar.png'
            ];

            // 获取门店信息
            $storeInfo = [
                'name' => $store->store_name
            ];

            $responseData = [
                'user_info' => $userInfo,
                'store_info' => $storeInfo,
                'vendor_list' => $vendorList
            ];

            return response()->json([
                'code' => 1,
                'message' => '获取供应商清单成功',
                'data' => $responseData
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 0,
                'message' => '获取供应商清单失败: ' . $e->getMessage()
            ]);
        }
    }
}